<?php

namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\Request;

class System extends Adminbase
{
    protected $add_edit_field;
    protected function initialize(){
        parent::initialize();
        $this->add_edit_field = [
            ['field'=>'s_key','title'=>'配置标识','type'=>'text','verify'=>'required','tips'=>'唯一不重复，字母+下划线'],
            ['field'=>'name','title'=>'配置名称','type'=>'text','verify'=>'required','tips'=>''],
            ['field'=>'content','title'=>'配置内容','type'=>'text','tips'=>'默认值'],
            ['field'=>'input_v','title'=>'预设参数','type'=>'textarea','tips'=>'单选/复选/下拉，需要预设参数，格式：key:value|key1:value1.....'],
            ['field'=>'description','title'=>'配置描述','type'=>'text','tips'=>''],
            ['field'=>'is_system','title'=>'系统内置','type'=>'select','verify'=>'required','tips'=>'','data'=>['1'=>'系统配置','2'=>'其他配置'],'value'=>'2'],
            ['field'=>'sort','title'=>'配置类型','type'=>'select','verify'=>'required','tips'=>'','data'=>config("otherconfig.system_type"),'value'=>'1'],
            ['field'=>'form_type','title'=>'表单类型','type'=>'select','verify'=>'required','tips'=>'','data'=>config("otherconfig.form_type"),'value'=>'1'],
            ['field'=>'status','title'=>'配置调用','type'=>'radio','verify'=>'required','tips'=>'','data'=>['1'=>'允许调用','2'=>'禁止调用'],'value'=>'1'],
            ['field'=>'order_by','title'=>'配置排序','type'=>'number','verify'=>'number','tips'=>'排序，值越小越靠前','value'=>'1']
        ];
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $sys_info = db('system')->order('order_by asc')->select();
        $sys_type = config("otherconfig.system_type");
        $new_array = [];
        foreach($sys_type as $k=>$v){
            foreach($sys_info as $k1=>$v1){
                if(in_array($v1['form_type'],['select','radio','checkbox']) && !empty($v1['input_v'])){//三个选项应具备预设参数，对预设值处理
                    if (strstr($v1['input_v'], '|')) {
                        $input = explode('|', $v1['input_v']);
                        foreach ($input as $k2 => $v2) {
                            if(strstr($v2, ':')){
                                $input[$k2] = explode(':', $v2);
                            }else{
                                unset($input[$k2]);
                            }
                        }
                        if($input){
                            $v1['input_v'] = $input;
                        }else{
                            unset($v1['input_v']);
                        }
                    }else{
                        if(strstr($v1['input_v'], ':')){
                            $input = explode(':', $v1['input_v']);
                            if($input){
                                $v1['input_v'] = $input;
                            }else{
                                unset($v1['input_v']);
                            }
                        }else{
                            unset($v1['input_v']);
                        }
                    }
                }elseif(in_array($v1['form_type'],['select','radio','checkbox']) && empty($v1['input_v'])){//缺失对应预设参数，过滤此配置
                    continue;
                }
                if($v1['form_type'] === 'checkbox' && !empty($v1['content'])){//复选框参数应为数组转字符串数据，所以回转换为array数据
                    $v1['content'] = explode(',', $v1['content']);
                }
                if($v1['sort'] === $k){
                    $new_array[$k][$k1] = $v1;
                }
            }
        }
        return view('index',['sys_type'=>$sys_type,'sys_array'=>$new_array]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request)
    {
        $data = $request->param();
        if(!$data || !is_array($data)){
            return json(['code'=>1,'msg'=>'数据错误']);
        }
        foreach($data as $k=>$v){
            $ck = db('system')->where('s_key',$k)->find();
            if($ck){
                if($ck['form_type'] === 'checkbox'){
                    $v = implode(',',$v);
                }
                db('system')->where('s_key',$k)->update(['content'=>$v]);
            }
        }
        return json(['code'=>200,'msg'=>'配置处理完成']);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        $id = $request -> post('id');
        if(!is_array($id)){
            if(!is_numeric($id)){
                return json(['code'=>1,'msg'=>'数据错误']);
            }else{
                $id = explode(',',$id);
            }
        }
        if(is_array($id)){
            foreach($id as $val){
                $old = db('system')->where('id',$val)->find();
                if($old){
                    if($old['is_system'] == 1){
                        return json(['code'=>1,'msg'=>'配置：'.$old['s_key'].'为系统配置禁止删除']);
                    }
                }else{
                    return json(['code'=>1,'msg'=>'存在非数据库数据，请核查']);
                }
            }
            $res = db('system')->delete($id);
            if($res){
                return json(['code'=>200,'msg'=>'删除成功']);
            }else{
                return json(['code'=>1,'msg'=>'删除失败']);
            }
        }else{
            return json(['code'=>1,'msg'=>'数据错误']);
        }
    }

    /**
     * 配置管理
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deploy(){
        $Prefix = [
            'is_system'=>[1=>'系统配置',2=>'其他配置'],
            'sort'=>config("otherconfig.system_type")
        ];
        $info = db('system')->order('id asc')->select();
        if($info && $Prefix){
            foreach($Prefix as $k=>$v){
                foreach($info as $k1=>$v1){
                    if(isset($v1[$k])){
                        $info[$k1][$k] = $v[$v1[$k]];
                    }
                    if($v1['is_system'] == 1){
                        $info[$k1]['no_delete'] = 1;
//                        $info[$k1]['no_edit'] = 1;
                    }
                }
            }
        }

        $filed = [
            ['field'=>'id','title'=>'ID'],
            ['field'=>'s_key','title'=>'配置标识'],
            ['field'=>'name','title'=>'配置名称'],
            ['field'=>'content','title'=>'配置内容'],
            ['field'=>'description','title'=>'配置描述'],
            ['field'=>'is_system','title'=>'系统内置'],
            ['field'=>'sort','title'=>'配置类型'],
            ['field'=>'status','title'=>'配置调用'],
            ['field'=>'order_by','title'=>'表单排序'],
            ['field'=>'create_at','title'=>'添加时间'],
            ['field'=>'update_at','title'=>'更新时间'],
        ];
        return view('public/list',['filed'=>$filed,'info'=>json_encode($info,JSON_UNESCAPED_UNICODE),'table'=>'table']);
    }
    public function edit(Request $request){
        $id = $request->param('id');
        if(!$id){
            return json(['code'=>1,'msg'=>'数据错误，need ID']);
        }
        $data = db('system')->where('id',$id)->find();
        if(!$data){
            return json(['code'=>1,'msg'=>'数据不存在']);
        }
        return view('public/edit',['filed'=>$this->add_edit_field,'info'=>$data,'operate'=>['update'=>'admin/system/deploy_update']]);
    }
    public function deploy_update(Request $request){
        $data = $request->param();
        if(!$data || !is_array($data)){
            return json(['code'=>1,'msg'=>'数据格式错误，need Array']);
        }
        foreach($data as $k=>$v){
            if(in_array($k,['s_key','name']) && empty($v)){
                return json(['code'=>1,'msg'=>'字段：'.$k.'必填！required']);
            }
            if($k === 's_key'){
                if(!preg_match('/^[a-zA-Z_]+$/', $v)){
                    return json(['code'=>1,'msg'=>'字段：'.$k.'只能是 大小写字母 + “_”']);
                }
            }
            $old = db('system')->where('s_key',$v)->where('id','<>',$data['id'])->find();
            if($old){
                return json(['code'=>1,'msg'=>'字段：'.$k.'不可重复！']);
            }
        }
        $old_info = db('system')->where('id',$data['id'])->find();
        if($old_info['is_system'] == 1){
            unset($data['is_system']);
            unset($data['sort']);
            unset($data['status']);
        }
        $res = $this->update_info('system',$data);
        return json($res);
    }
    public function save(){
        return view('public/add',['filed'=>$this->add_edit_field]);
    }
    public function add(Request $request){
        $data = $request->param();
        if(!$data || !is_array($data)){
            return json(['code'=>1,'msg'=>'数据格式错误，need Array']);
        }
        foreach($data as $k=>$v){
            if(in_array($k,['s_key','name']) && empty($v)){
                return json(['code'=>1,'msg'=>'字段：'.$k.'必填！required']);
            }
            if($k === 's_key'){
                if(!preg_match('/^[a-zA-Z_]+$/', $v)){
                    return json(['code'=>1,'msg'=>'字段：'.$k.'只能是 大小写字母 + “_”']);
                }
                $old = db('system')->where('s_key',$v)->find();
                if($old){
                    return json(['code'=>1,'msg'=>'字段：'.$k.'不可重复！']);
                }
            }
        }
        $res = $this->add_info('system',$data);
        return json($res);
    }
}
